const { ccclass, property } = cc._decorator;

@ccclass
export default class CallbackSlider extends cc.Component {
    @property
    startVal = 0;
    @property
    rangeVal = 1;
    @property
    callbackName = "";

    @property(cc.Node)
    target: cc.Node = null;

    @property(cc.Slider)
    get slider() {
        return this.getComponent(cc.Slider) || this.addComponent(cc.Slider);
    }
    @property(cc.Label)
    lb: cc.Label = null;

    protected onLoad(): void {
        let evt = new cc.Slider.EventHandler();
        evt.component = "callback_slider";
        evt.handler = "onSlider";
        evt.target = this.node;
        this.slider.slideEvents.push(evt);
    }

    refresh() {
        let val = this.value;
        if (this.lb) {
            this.lb.string = `${val.toFixed(4)}`;
        }
    }

    get value() {
        return this.startVal + this.slider.progress * this.rangeVal;
    }

    onSlider() {
        let val = this.value;
        let target = this.target || this.node;
        target.getComponents(cc.Component).forEach(com => {
            if (com[this.callbackName]) {
                com[this.callbackName](val);
            }
        });
        this.refresh();
    }
};